<script setup lang="ts">
import { ref, watch } from "vue";

type SelectIem = {
  value: number | string;
  label: string;
  check: boolean;
};
let props = defineProps({
  options: {
    type: Array<SelectIem>,
    required: true,
  },
  width: {
    type: Number,
    default() {
      return 220;
    },
  },
  roleIds: {
    type: Array<number | string>,
    default() {
      return [];
    },
  },
});
let selectWidth = "width:" + props.width + "px";
const emit = defineEmits(["selected"]);
let selectedOptions = ref<Array<number | string>>([]);
const isChecked = (item: SelectIem) => {
  if (item.check && selectedOptions.value.indexOf(item.value) === -1) {
    selectedOptions.value.push(item.value);
  } else if (!item.check) {
    selectedOptions.value.forEach((value, index) => {
      if (value === item.value) {
        selectedOptions.value.splice(index, 1);
      }
    });
  }
  emit("selected", selectedOptions.value);
};
const removeTag = (value: number | string) => {
  props.options.forEach((item) => {
    if (item.value === value) {
      item.check = false;
    }
  });
  emit("selected", selectedOptions.value);
};
const selectAll = (check: boolean) => {
  if (check) {
    selectedOptions.value = [];
    props.options.forEach((item) => {
      item.check = true;
      selectedOptions.value.push(item.value);
    });
    console.log(selectedOptions.value);
  } else {
    let arr: Array<number | string> = [];
    props.options.forEach((item) => {
      item.check = false;
      if (!selectedOptions.value.includes(item.value)) {
        arr.push(item.value);
      }
    });
    selectedOptions.value = arr;
  }
  emit("selected", selectedOptions.value);
};
const clear = () => {
  selectedOptions.value = [];
};
watch(
  () => props.roleIds,
  () => {
    selectedOptions.value = props.roleIds;
    props.roleIds.forEach((item) => {
      props.options.find((value) => {
        if (value.value === item) {
          value.check = true;
        }
      });
    });
  },
  { immediate: true }
);
defineExpose({
  clear,
});
</script>

<template>
  <el-select
    v-model="selectedOptions"
    multiple
    placeholder="请选择"
    :propper-append-to-body="false"
    :style="selectWidth"
    @remove-tag="removeTag"
    style="width: 100%"
  >
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    >
      <el-checkbox v-model="item.check" @change="isChecked(item)">
        {{ item.label }}
      </el-checkbox>
    </el-option>
    <div class="is-all">
      <div @click="selectAll(true)">全选</div>
      <div @click="selectAll(false)">反选</div>
    </div>
  </el-select>
</template>

<style scoped lang="scss">
.is-all {
  display: flex;
  padding-left: 10px;
  div {
    cursor: pointer;
    margin: 6px 10px;
    transition: 0.2s;
    &:hover {
      opacity: 0.7;
    }
  }
}
</style>
